package com.cy.embeddingdemo.service;

import com.alibaba.fastjson2.JSON;
import com.cy.embeddingdemo.config.MinioConfig;
import com.cy.embeddingdemo.dto.MineruDto;
import com.cy.embeddingdemo.util.MinerUutil;
import com.cy.embeddingdemo.util.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

import static com.cy.embeddingdemo.util.MinerUutil.deleteFile;
import static org.codehaus.plexus.util.FileUtils.deleteDirectory;

@Service
public class TaskManagerService {

    @Autowired
    private RedisUtil redisUtil;

    private static String CREATE_TASK_URL = "https://mineru.net/api/v4/extract/task";
    private static String CHECK_TASK_URL = "https://mineru.net/api/v4/extract/task/";
    private static String AUTHORIZATION_TOKEN = "Bearer eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ.eyJqdGkiOiI4MjYwMDQ4OSIsInJvbCI6IlJPTEVfUkVHSVNURVIiLCJpc3MiOiJPcGVuWExhYiIsImlhdCI6MTc0MzMwMTgzOCwiY2xpZW50SWQiOiJsa3pkeDU3bnZ5MjJqa3BxOXgydyIsInBob25lIjoiIiwib3BlbklkIjpudWxsLCJ1dWlkIjoiMmRkYWY2YmUtM2Q3ZC00MDA1LTg3MjQtZTA4YmNjYTBiNjk0IiwiZW1haWwiOiIiLCJleHAiOjE3NDQ1MTE0Mzh9.0l7hUfXDCcc-SDBi5LNXHqTAa7auIvX-nlv0qQuM20DlSd3PnG9wVHV2SmB9763IQjFeYvLafj61BAl7ngA2hQ";

    /**
     * 传入文件路径，提交 MinerU 去处理
     * @param fileUrl
     * @return
     */
    public String crateMinerUTask(String fileUrl){


        // String fileUrl = minioConfig.getUrl() + "/"+minioConfig.getBucketName()+"/" + fileName;
        // String fileUrl =   "http://1.15.135.14:9000/" +minioConfig.getBucketName()+"/" + fileName;

        try {
            // 创建 HttpClient 实例
            HttpClient client = HttpClient.newHttpClient();


            // 设置请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Authorization",  AUTHORIZATION_TOKEN);
            // 设置请求体
            Map<String, Object> data = new HashMap<>();
            data.put("url", fileUrl );
            data.put("is_ocr", true);
            data.put("enable_formula", false);

            // 使用 Jackson 将 Map 转换为 JSON 字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonData = objectMapper.writeValueAsString(data);

            // 创建 POST 请求
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(CREATE_TASK_URL))
                    .headers(headers.entrySet().stream()
                            .flatMap(entry -> Stream.of(entry.getKey(), entry.getValue()))
                            .toArray(String[]::new))
                    .POST(HttpRequest.BodyPublishers.ofString(jsonData))
                    .build();

            // 发送请求并获取响应
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            // 打印响应状态码
            System.out.println("Status Code: " + response.statusCode());

            // 打印响应头
            HttpHeaders httpHeaders = response.headers();
            httpHeaders.map().forEach((k, v) -> System.out.println(k + ":" + v));

            // 打印响应体
            System.out.println("Response Body: " + response.body());

            // 解析响应体中的 "data" 字段
            Map<String, Object> responseBody = objectMapper.readValue(response.body(), Map.class);
            if (responseBody.containsKey("data")) {

                LinkedHashMap<String,String> responseBodyMap
                        = (LinkedHashMap<String, String>) responseBody.get("data");
                String taskID = responseBodyMap.get("task_id");
                redisUtil.putTask(taskID); //将 任务id 存入 redis

                return taskID;
            } else {
                System.out.println("No 'data' field in response.");

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {

        String taskid ="26778770-d06e-467c-b89d-867eb7ecd765";
        String analyzedFolder = "unzipped_files/" + taskid;


        // 使用 Path 对象表示文件路径
        Path filePath = Paths.get(analyzedFolder+ "/full.md");

        try {
            // 使用 Files.readString 方法读取文件内容（Java 11+）
            String content = Files.readString(filePath);


            // 数据处理完删除文件夹
            // deleteDirectory(analyzedFolder);

        } catch (IOException e) {
            System.err.println("Error reading the file: " + e.getMessage());
        }



    }



    // 查询任务状态的方法,当任务已经完成就把 该 taskid 从 redis 中删除
    public void checkTaskStatus(String taskId) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(CHECK_TASK_URL + taskId))
                .header("Content-Type", "application/json")
                .header("Authorization",  AUTHORIZATION_TOKEN)
                .GET()
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        // 解析响应体中的 JSON 数据
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> responseBody = objectMapper.readValue(response.body(), Map.class);
        String state = (String) ((Map<String, Object>) responseBody.get("data")).get("state");


        if ("done".equals(state)) {

            // 获取 full_zip_url
            String fullZipUrl = (String) ((Map<String, Object>) responseBody.get("data")).get("full_zip_url");
            System.out.println("Full ZIP URL: " + fullZipUrl);

            String tempFileName = fullZipUrl.substring(fullZipUrl.lastIndexOf("/") + 1);
            // 下载文件
            MinerUutil.downloadFile(fullZipUrl, tempFileName);
            // 解压文件
            MinerUutil.unzipFile(tempFileName, "unzipped_files/"+tempFileName.replace(".zip",""));


            processPDFContent(taskId);



            //从 redis 去除该 taskid
            redisUtil.removeTask(taskId); //将 任务id 去除 redis
        }
    }


    public void processPDFContent(String taskId) throws IOException, InterruptedException {




        String analyzedFolder = "unzipped_files/" + taskId;


        // 使用 Path 对象表示文件路径 unzipped_files/f7acd625-0850-4579-9460-d695bb5cadd1/f7acd625-0850-4579-9460-d695bb5cadd1_content_list.json
        // Path filePath = Paths.get(analyzedFolder+ "/full.md");
        Path filePath = Paths.get(analyzedFolder+ "/"+taskId+"_content_list.json");

        try {
            // 使用 Files.readString 方法读取文件内容
            String content = Files.readString(filePath);
            List<MineruDto> mineruDtos = JSON.parseArray(content, MineruDto.class);

            //提取三元组


            System.out.println();


            // 数据处理完删除文件夹
            // deleteDirectory(analyzedFolder);

        } catch (IOException e) {
            System.err.println("Error reading the file: " + e.getMessage());
        }


    }
}
